﻿using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Columns
{
    /// <summary>
    /// Adds a <see cref="Column"/> to a <see cref="Table"/> in the underlying database.
    /// </summary>
    public static class AddCommand
    {
        private const string Sql = @"ALTER TABLE `{0}` ADD COLUMN {1}";

        /// <summary>
        /// Executes the command to add a <see cref="Column"/> to a <see cref="Table"/>.
        /// </summary>
        /// <param name="column">The column.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <param name="connection">The connection.</param>
        public static void Execute(Column column, string tableName, Connection connection)
        {
            var sql = Sql;

            if (column.IsFirst)
            {
                sql += " FIRST";
            }
            else if (!string.IsNullOrEmpty(column.After))
            {
                sql += " AFTER `" + column.After + "`";
            }


            if (column.PrimaryKey)
            {
                sql += string.Format(",ADD PRIMARY KEY(`{0}`);", column.Name);
            }
            else
            {
                sql += ";";    
            }
            

            connection.ExecuteNonQuery(sql, null, tableName, column.ToDefinitionSql());
        }
    }
}